<route lang="json5">
{
  style: {
    navigationBarTitleText: '掌上建议详情',
  },
}
</route>
<template>
  <!-- 头部卡片 -->
  <wd-card type="rectangle" class="mb-16">
    <view class="content pt-8 text-#000">
      <!-- 🌟 置顶标签与标题布局 -->
      <view class="flex items-start">
        <!-- <view class="content-sticky">置顶</view> -->
        <view class="text-16px font-semibold ml-4">{{ detailData.title }}意见</view>
      </view>

      <!-- 🌟 三列信息布局 -->
      <view class="flex justify-between text-12px mt-8">
        <view class="text-#666">{{ detailData.submitterName }}</view>
        <view class="text-#666">{{ detailData.submittedAt }}</view>
        <view class="text-#666" v-if="showTibetan">
          共收到{{ detailData?.replyList?.length }}条意见
        </view>
      </view>
    </view>
  </wd-card>

  <!-- 内容卡片 -->
  <wd-card type="rectangle" class="mb-16">
    <view class="content text-#000">
      <view class="text-14px leading-6">
        {{ detailData.content }}
      </view>

      <!-- 🌟 相关资料区域 -->
      <view class="mt-16">
        <view class="text-red text-14px font-medium">相关资料</view>

        <!-- ✅ 图片横向展示 -->
        <view class="flex flex-wrap gap-4 mt-8" v-if="imageList.length > 0">
          <image
            v-for="(img, index) in imageList"
            :key="'img-' + index"
            :src="img.url"
            class="w-24 h-24 rounded cursor-pointer"
            mode="aspectFill"
            @click="previewImage(index)"
          />
        </view>

        <!-- ✅ 文档列表展示 -->
        <!-- ✅ 文档列表展示（支持点击预览）-->
        <view class="mt-8 space-y-4" v-if="docList.length > 0">
          <view
            v-for="(doc, index) in docList"
            :key="'doc-' + index"
            class="flex items-center cursor-pointer"
            @click="handlePreviewDoc(doc.url)"
          >
            <wd-icon name="file-paste" size="24px"></wd-icon>
            <!-- <image src="/static/icon-file.png" class="w-6 h-6 mr-2" /> -->
            <text class="text-14px break-all text-blue underline">
              {{ doc.name }}
            </text>
          </view>
        </view>
      </view>
    </view>
  </wd-card>

  <!-- 意见反馈卡片 -->
  <wd-card type="rectangle" v-if="store.isRepresentative === 1 && showTibetan">
    <!-- 🌟 标题红色竖条 -->
    <template #title>
      <view class="flex items-center">
        <view class="w-2 h-8 bg-red mr-4"></view>
        <text class="">共收到</text>
        <text class="text-red">{{ detailData?.replyList?.length }}</text>
        <text class="">条意见</text>
      </view>
    </template>

    <!-- 🌟 人大代表反馈 -->
    <view class="content pt-8 text-#000">
      <view class="flex items-start mb-16" v-for="(item, index) in detailData.replyList">
        <image v-if="item.avatar_url" class="w-10 h-10 rounded-full mt-2" :src="item.avatar_url" />
        <image v-else class="w-10 h-10 rounded-full mt-2" src="/static/avatar-default.png" />
        <view class="flex-1 ml-4">
          <view class="text-18px mb-2">{{ item.name }}</view>
          <view class="flex items-center justify-between text-#ccc">
            <view class="">{{ item.group_name }}</view>
            <view class="">提交时间 {{ item.reply_time }}</view>
          </view>

          <view class="text-16px font-medium mt-8">{{ item.reply_content }}</view>
          <view class="text-16px font-medium mt-2">{{ item.representative_zw_name }}</view>
        </view>
      </view>
    </view>
  </wd-card>
  <view
    class="text-18px flex items-center gap-2 advice-tip"
    style="background-color: #ffefef; padding: 1.5rem; margin: 20px; border-radius: 25px"
  >
    <text>
      您好！感谢您为和美共和文旅事业提出的宝贵建议，针对您提出的问题，我们将会持续跟踪监督整改。
    </text>
  </view>
</template>
<script setup lang="ts">
import { onLoad, onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { palmAdviceById, replyList } from '@/api/palmAdvice'
import { repPositionList } from '@/api/representative'
import { formatDate, parseTimeToTimestamp, formatDateTime } from '@/utils/date'

// 获取环境变量
const showTibetan = import.meta.env.VITE_SHOW_TIBETAN === 'true'
const appTitle = ref(import.meta.env.VITE_APP_TITLE || 'Unibest Login')
const appLogo = ref(import.meta.env.VITE_APP_LOGO || '/static/logo.png')
const appBackground = ref(import.meta.env.VITE_APP_LOGO || '/static/bg.png')
const appBackgroundColor = ref(import.meta.env.VITE_APP_LOGO || '/static/bgcolor.png')

const store = useUserStore()

const isLoading = ref(false) // 避免重复请求
const positionList = ref<any[]>([])

const detailId = ref(null)
const tenantId = ref(null)
const detailData = ref<any>({
  attachmentUrlList: [],
  replyList: [],
})

onLoad(async (options) => {
  console.log('options', options)
  tenantId.value = options?.tenantId
  detailId.value = options?.id
  console.log(' detailId.value', detailId.value)
  await getPositionList()
  if (detailId.value) getPalmAdviceById(detailId.value)
})
//获取人大代表分组列表
const getPositionList = async () => {
  try {
    const res = await repPositionList()
    if (res.code === 0) {
      positionList.value = res.data
    }
  } catch (error) {}
}

const previewImage = (index: number) => {
  uni.previewImage({
    current: imageList.value[index].url,
    urls: imageList.value.map((img) => img.url),
  })
}

//获取详情数据
const getPalmAdviceById = async (feedbackId: number) => {
  try {
    const res = await palmAdviceById(feedbackId)
    if (res.code === 0) {
      detailData.value = res.data || {}
      if (detailData.value.content) {
        detailData.value.content = detailData.value.content.replace(/<[^>]+>/g, '')
      }
      if (detailData.value.groupId) {
        detailData.value.groupName = positionList.value.find(
          (groupItem) => groupItem.groupId === detailData.value.groupId,
        ).groupName
        const res = await replyList(detailData.value.feedbackId)
        if (res.code === 0) {
          detailData.value.replyList = res.data.map((item) => ({
            ...item,
            reply_content: item.reply_content.replace(/<[^>]+>/g, ''),
            reply_time: formatDateTime(item.reply_time),
          }))
        }
      }
      console.log('detailData.value', detailData.value)
    }
  } catch (error) {
    console.error(error)
  } finally {
    isLoading.value = false
  }
}
const isImage = (url: string): boolean => {
  return /\.(png|jpe?g|gif|bmp|webp|svg)$/i.test(url)
}
function getFileName(path: string): string {
  return decodeURIComponent(path.split('/').pop() || '未知文件')
}
// 点击文档预览
const handlePreviewDoc = (url: string) => {
  // #ifdef MP-WEIXIN
  uni.downloadFile({
    url,
    success: (res) => {
      if (res.statusCode === 200) {
        uni.openDocument({
          filePath: res.tempFilePath,
          success: () => {
            console.log('文档打开成功')
          },
          fail: (err) => {
            console.error('文档打开失败', err)
            uni.showToast({ title: '预览失败', icon: 'none' })
          },
        })
      } else {
        uni.showToast({ title: '下载失败', icon: 'none' })
      }
    },
    fail: () => {
      uni.showToast({ title: '下载失败', icon: 'none' })
    },
  })
  // #endif

  // #ifdef H5
  window.open(url, '_blank')
  // #endif
}
const imageList = computed(
  () => detailData.value.attachmentFiles?.filter((item) => isImage(item.url)) || [],
)
const docList = computed(
  () => detailData.value.attachmentFiles?.filter((item) => !isImage(item.url)) || [],
)
</script>

<style>
/* 🌟 精细化样式调整 */
.content-sticky {
  background: #ff4444;
  border-radius: 4rpx;
  padding: 4rpx 12rpx;
  font-size: 24rpx;
  color: white;
  line-height: 1.5;
}

/* 🌟 头像样式 */
.rounded-full {
  border: 1rpx solid #eee;
}

/* 🌟 首行缩进样式 */
.advice-tip text {
  text-indent: 2em;
  display: block;
}
</style>
